﻿using DX.ViewModels;
using DX.Views;
using System;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;

namespace DX
{
    public partial class ViewForm : Form, IView, IAttach, IDetach
    {
        public ViewForm()
        {
            ViewModelBindingSource = new BindingSource();
            DataContext = ViewModelBindingSource;
            InitializeComponent();

        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Minor Code Smell", "S1104:Fields should not have public accessibility", Justification = "<挂起>")]
        public BindingSource ViewModelBindingSource;
        /// <summary>
        /// 
        /// </summary>
        [Category("MVVM")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [Browsable(false)]
        public ViewModel ViewModel
        {
            get
            {
                return ViewModelBindingSource?.DataSource as ViewModel;
            }

            protected set
            {
                if (value == null) return;

                ViewModelBindingSource.DataSource = value;
            }
        }

        public void SetViewModelCloseState(bool isclose)
        {
            ViewModel.actuallyClosing = isclose;
        }

        protected override void OnClosed(EventArgs e)
        {
            OnDetachView(this, ViewModel);
            base.OnClosed(e);
        }



        protected virtual void OnAttachView(IView view, IViewModel viewModel)
        {
            this.ViewModel = viewModel as ViewModel;
        }

        protected virtual void OnDetachView(IView view, IViewModel viewModel)
        {
            this.ViewModel = null;
        }
        void IAttach.Attach(IView view, IViewModel viewModel)
        {
            OnAttachView(view, viewModel);
        }

        void IDetach.Detach(IView view, IViewModel viewModel)
        {
            OnDetachView(view, viewModel);
        }

    }
}
